import {
	login,
	wechartLogin
} from "../../common/api/oauthServer/user";
import operate from "../../common/utils/operate";
import {
	getToken,
	setToken,
	removeToken
} from "../../common/utils/auth";
const state = {
	token: '',
	userId: '',
	username: '',
	nickname: '',
	headImgUrl: ''
}

const mutations = {
	SET_USERINFO: (state, data) => {
		console.log(data)
		state.token = getToken()
		state.username = data.username
		state.userId = data.userId
		state.nickname = data.nickname
		state.headImgUrl = data.headImgUrl
	},
	CLEAR_USERINFO: state => {
		state.token = ''
		state.username = ''
		state.nickname = ''
		state.headImgUrl = ''
	}
}

const actions = {
	login({
		commit
	}, loginData) {
		const {
			username,
			password,
			grantType
		} = loginData
		return new Promise((resolve, reject) => {
			let loginData = {}
			loginData.username = username
			loginData.password = password
			loginData.grant_type = grantType
			login(loginData).then(res => {
				console.log(res)
				setToken(operate.tokenPrefix + res.access_token)
				commit('SET_USERINFO', res)
				commit('CLEAR_CHARTS')
				resolve()
			}).catch(err => {
				reject(err)
			})
		})
	},
	wechartLogin({
		commit
	}, wxOpenId) {
		return new Promise((resolve, reject) => {
			wechartLogin(wxOpenId).then(res => {
				setToken(operate.tokenPrefix + res.access_token)
				commit('SET_USERINFO', res)
				commit('CLEAR_CHARTS')
				resolve()
			}).catch(err => {
				reject(err)
			})
		})
	},
	loginOut({
		commit
	}) {
		commit('CLEAR_USERINFO')
		removeToken()
	}
}

export default {
	namspaced: true,
	state,
	mutations,
	actions
}
